/* eslint-disable react/forbid-prop-types */
/**
 * @file 指标echart
 * @author liushuang04@baijaihulian.com
 * @date 2019-11-19
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import echarts from 'echarts';
import shortid from 'shortid';
import './index.styl';

class DataEchart extends Component {
    static propTypes = {
        echartEl: PropTypes.object
    };

    constructor(props) {
        super(props);
        this.state = {
            options: null,
            id: shortid.generate()
        };
    }

    static getDerivedStateFromProps(props, state) {
        const {data} = props;
        if (data !== null) {
            return {
                options: {...data}
            };
        }
        return null;
    }

    componentDidMount() {
        const {options, id} = this.state;
        const {echartEl} = this.props;
        echartEl.current = echarts.init(document.getElementById(`echarts${id}`));
        if (options !== null) {
            echartEl.current.setOption(options, true);
        }
        // 实现图表对象与窗口对象的尺寸一致的情况
        window.onresize = echartEl.current.resize;
    }

    getSnapshotBeforeUpdate() {
        const {options} = this.state;
        const {echartEl} = this.props;
        if (options !== null) {
            echartEl.current.setOption(options, true);
        }
        return true;
    }

    render() {
        const {id} = this.state;
        return (
            <div className="echartMain">
                <div className="echarts" id={`echarts${id}`}></div>
            </div>
        );
    }
}

DataEchart.defaultProps = {
    echartEl: React.createRef()
};

export default DataEchart;
